package com.example.cpl.gjc;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.VideoView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class button_2 extends AppCompatActivity {
    //声明控件
    private VideoView mVideoView;
    private static final String TAG = "TAG";
    private static final String IP_HEAD = "192.168.31.";
    //    Toast tst;
    int err_i=0;
    private int wi=0,time=10,dev_num=1;
    private Button button_send,button_add,button_minus,btn_Back,button_send_specify,button_add_specify,button_minus_specify;
    static Handler mHandler;
    static ExecutorService mThreadPool;
    static Socket socket;  // Socket变量
    static OutputStream outputStream;
    //    public boolean a;
    private TextView btn2_login_name,btn2_online_num;
    private TextView tv_time,tv_specify;
    private int a=1;
    //    String rec;        // 接收服务器发送过来的消息
    InputStream is;         // 输入流对象
    InputStreamReader isr ; // 输入流读取器对象
    static BufferedReader br ;     // 输入流读取器对象

    public int m_count=0;       //声明进度条对话框
    public String ssidd ="";


    ProgressDialog m_pDialog;
    public void initWidght(){
        btn_Back=(Button)findViewById(R.id.btn2_back);

        button_send=(Button)findViewById(R.id.button_send);
        button_add=(Button)findViewById(R.id.button_add);
        button_minus=(Button)findViewById(R.id.button_minus);
        tv_time=(TextView)findViewById(R.id.btn2_tv_time);

        button_send_specify=(Button)findViewById(R.id.button_send_specify);
        button_add_specify=(Button)findViewById(R.id.button_add_specify);
        button_minus_specify=(Button)findViewById(R.id.button_minus_specify);
        tv_specify=(TextView)findViewById(R.id.tv_specify);
        btn2_login_name=(TextView)findViewById(R.id.btn2_login_name);
        btn2_online_num=(TextView)findViewById(R.id.btn2_online_num);
        btn2_login_name.setText(teach_center.who);
        btn2_online_num.setText(""+device_manage.dev_num+"");


    }

    public void ProgressShow(int num1)
    {
        m_count = 0;

        m_pDialog = new ProgressDialog(button_2.this);// 创建ProgressDialog对象
        m_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 设置进度条风格，风格为长形
        m_pDialog.setTitle("发送中..."); // 设置ProgressDialog 标题
        m_pDialog.setMessage("正在自动发题 请等待");  // 设置ProgressDialog 提示信息
        m_pDialog.setIcon(R.drawable.icon); // 设置ProgressDialog 标题图标
        m_pDialog.setMax(num1);// 设置进度条最大值
//        m_pDialog.setProgress(50);// 设置ProgressDialog 进度条进度
        m_pDialog.setIndeterminate(false);  // 设置ProgressDialog 的进度条是否不明确
        m_pDialog.setCancelable(false); // 设置ProgressDialog 是否可以按退回按键取消
        m_pDialog.show(); // 让ProgressDialog显示
    }
//    public void Connect_WIFI_TCP(String  ssid, String password,int type,final String ip, final int port) {
//
//
//        //a=0;
//        Log.d(TAG,"WiFi连接中...");
//        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
//        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//        WifiAdmin wifiAdmin = new WifiAdmin(button_2.this);
//
//        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
//        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//        if (!(mWifi.isConnected())||(!(wifiInfo.getSSID().equals("\"" +ssid+"\"")))){
//            if(wifiInfo.getSSID().equals("<unknown ssid>")) {    //这个条件说明没有打开WiFi
//                wifiAdmin.openWifi();
//            }
//            wifiAdmin.disconnectWifi(wifiAdmin.getNetworkId());
//            wifiAdmin.addNetwork(wifiAdmin.createWifiConfig("" + ssid + "", "" + password + "", type));
//            //这里加延时3秒
//            Log.d(TAG,"延时开始");
//            try {
//                Thread.sleep(3500);
//            } catch (InterruptedException e){
//                e.printStackTrace();
//            }Log.d(TAG,"延时结束");
//
//            Log.d(TAG,"判断WiFi是否连接");
//            if((wi<1)&& ((!wifiInfo.getSSID().equals("\"" +ssid+"\""))||(!(mWifi.isConnected()))) )
//            {
//                wi++;
//                Log.d(TAG,"WiFi连接失败 尝试重新连接.....");
//                Log.d(TAG,"WiFi重新连接次数"+wi);
//                Connect_WIFI_TCP("" + ssid + "", "" + password + "", type,""+ip+"", port);
//
//            }
//            wi=0;
//        }
//        if ((mWifi.isConnected())) {
//            Log.d(TAG, "WiFi连接成功!");
//            Connect_Tcp(""+ip+"", port);
//
//            //这里加入延时 给TCP反应时间   延迟下一个WiFi的连接
//        }
//        else {
//            a++;
//            if(a%2==0) {
//                a=0;
//                ssidd = ssidd + ssid.substring(ssid.indexOf("j") + 1) + ",";
//            }
//            Log.d(TAG, "——WiFi:  "+ ssid + "  没有找到........0.0");
//        }
//    }

    public void Connect_Tcp(final String ip, final int port) {
        Log.d(TAG,"TCP连接中...");
//        mThreadPool.execute(new Runnable() {
//            @Override
//            public void run() {
        try {

            socket = new Socket(""+ip+"",port);
            Log.d(TAG,"TCP连接成功");
            is = socket.getInputStream();             // 步骤1：创建输入流对象InputStream
            isr = new InputStreamReader(is);          // 步骤2：创建输入流读取器对象 并传入输入流对象
            br = new BufferedReader(isr);             // 该对象作用：发送数据
            outputStream = socket.getOutputStream();  // 步骤2：写入需要发送的数据到输出流对象中
            outputStream.write((time+",5555555555555555555555555555").getBytes("utf-8"));    // 数据的结尾加上换行符才可让服务器端的readline()停止阻塞
            Log.d(TAG,"——自动出题："+time+"+55");
//                    outputStream.write(("start" +wi+ "\n").getBytes("utf-8"));    //可以发送int类型的
            // 步骤3：发送数据到服务端
            outputStream.flush();
            Log.d(TAG,"TCP数据发送成功");
            socket.close();          //发送完数据后断开连接
            Log.d(TAG,"TCP已成功断开!");
            m_count+=1;
            m_pDialog.setProgress(m_count);

        } catch (IOException e) {

            e.printStackTrace();
        }



        Log.d(TAG,"——进度条进度为 "+m_count);
//            }
//        });
    }

    @SuppressLint("HandlerLeak")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_button_2);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);





//        mVideoView= (VideoView) findViewById(R.id.videoView2);
//
//         Uri vUri = Uri.parse("android.resource://" + getPackageName() + "/" +R.raw.hn);
//        mVideoView.setVideoURI(vUri);
//        mVideoView.setMediaController(new MediaController(button_2.this));
//        mVideoView.start();
//
//        MediaController mc = new MediaController(this);     //隐藏videoview进度条或者控制部分
//        mc.setVisibility(View.INVISIBLE);
//        mVideoView.setMediaController(mc);
//
//        //监听视频播放完的代码
//        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//            @Override
//            public void onCompletion(MediaPlayer mPlayer) {
//                // TODO Auto-generated method stub
//                mPlayer.start();
//                mPlayer.setLooping(true);           //循环播放
//            }
//        });
        initWidght(); //关联
        tv_time.setText(""+time+"");
        tv_specify.setText(""+dev_num+"");
        mThreadPool = Executors.newCachedThreadPool();   // 初始化线程池

        mHandler = new Handler()
        {                    // 实例化主线程,用于更新接收过来的消息
            @Override
            public void handleMessage(android.os.Message msg)
            {
                Log.d(TAG, "button接收obj= "+msg.obj);
                Log.d(TAG, "button接收what= "+msg.what);

                switch (msg.what){
                    case 0x01:
                        AlertDialog dlg = new AlertDialog.Builder(button_2.this)
                                .setIcon(R.drawable.icon)
                                .setTitle("发送状态")
                                .setMessage("成功：" + m_count + "台，失败："+ssidd)
                                .setPositiveButton("确定", null)
                                .create();
                        dlg.show();
                        msg.what=0;
                        break;

                }
            }
        };
        btn_Back.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Intent intent = new Intent(button_2.this, MainActivity.class);
                startActivity(intent);
//                overridePendingTransition(R.anim.abc_slide_out_bottom, R.anim.abc_slide_in_bottom);
            }
        });

        button_add.setOnClickListener(new View.OnClickListener()
        {
            //            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View view)
            {
                time+=5;
                if(time>90)
                {
                    time=90;
                }
                tv_time.setText(""+time+"");
                Log.d(TAG,"——设置的时间= "+time);
            }
        });

        button_minus.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                time-=5;
                if(time<10)
                {
                    time=10;
                }
                tv_time.setText(""+time+"");
                Log.d(TAG,"——设置的时间= "+time);
            }
        });

        button_add_specify.setOnClickListener(new View.OnClickListener()
        {
            //            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View view)
            {
                dev_num+=1;
                if(dev_num>25)
                {
                    dev_num=25;
                }
                tv_specify.setText(""+dev_num+"");
                Log.d(TAG,"——设置的设备= "+dev_num);
            }
        });

        button_minus_specify.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                dev_num-=1;
                if(dev_num<1)
                {
                    dev_num=1;
                }
                tv_specify.setText(""+dev_num+"");
                Log.d(TAG,"——设置的设备= "+dev_num);
            }
        });
        button_send.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                ProgressShow(25);
                new Thread()
                {
                    public void run(){
//                        Message msg=new Message();
//                        msg.what=0x01;//标识
//                        msg.obj="发送中...";
                        ssidd ="";
                        int id=0;
                        for(int a=0;a<25;a++) {
                                id=100+a;
                                Connect_Tcp(IP_HEAD + (a+100), 8080);

                        }

                        m_pDialog.cancel();     //关闭进度条对话框

                        Message msg=new Message();
                        msg.what=0x01;
//                        msg.arg1=1;
                        mHandler.sendMessage(msg);
                    }
                }.start();
            }


        });
        button_send_specify.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                ProgressShow(1);
                new Thread()
                {
                    public void run(){
//                        Message msg=new Message();
//                        msg.what=0x01;//标识
//                        msg.obj="发送中...";
                        ssidd ="";

                        int id=dev_num+100;
                        Connect_Tcp(IP_HEAD + (dev_num+100), 8080);


                        m_pDialog.cancel();     //关闭进度条对话框
                        Message msg=new Message();
                        msg.what=0x01;
//                        msg.arg1=1;
                        mHandler.sendMessage(msg);
                    }
                }.start();
            }


        });

    }

    @Override
    protected void onRestart() {
        super.onRestart();
//        mVideoView.start();
//
//        //监听视频播放完的代码
//        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//            @Override
//            public void onCompletion(MediaPlayer mPlayer) {
//                // TODO Auto-generated method stub
//                mPlayer.start();
//                mPlayer.setLooping(true);           //循环播放
//            }
//        });
    }

    @SuppressLint("PrivateResource")
    @Override
    public void onBackPressed() {       //重写back按键
        super.onBackPressed();

        overridePendingTransition(R.anim.abc_slide_in_bottom, R.anim.abc_slide_out_bottom);

        wi=0;time=10;dev_num=1;
//        mThreadPool.execute(new Runnable() {    // 利用线程池直接开启一个线程 & 执行该线程
//            @Override
//            public void run() {
//                try {
//
//                    outputStream = socket.getOutputStream();
//                    outputStream.write(("end"+"\n").getBytes("utf-8"));
//                    outputStream.flush();
//                    socket.close();             //断开TCP
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
        System.out.println("按下了back返回键，变量清零");
        return;
    }
}